package com.doone.telmarket.action.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import com.doone.basefun.DocryptoSecret;
import com.doone.telmarket.action.admin.BaseActionSupport;
import com.doone.telmarket.action.admin.ServiceAction;
import com.doone.telmarket.domain.UserInfo;
import com.opensymphony.xwork2.ActionContext;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @package com.doone.telmarket.action.web;
 * @author 甘雨波
 * @description 登陆用ACTION
 * @date 2009-10-21
 */
public class LoginAction extends BaseActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String cityCode;
	
	private String accnbr;
	
	private String linkedNbr;
	
	private String loginType;
	
	private String timdeStr;
	
	private String checkStr;
	
	private String errorMsg;
	
	private String userName;
	
	private String passWord;
	
	private String checkWord;
	
	
	Logger log = Logger.getLogger(ServiceAction.class);
	
	
	@Action(value = "redirectPage", results = {
			@Result(name = "success", location = "/web/index.htm"),
			@Result(name = "error", location = "/web/error.jsp") })
	public String redirectPage(){
		
		try{
			UserInfo user = new UserInfo();
			user.setCityCode(cityCode);
			user.setAccnbr(accnbr);
			
			String result = identityVisa(cityCode,accnbr,loginType,timdeStr,checkStr);
			
			//log.info(result);
			
			if(result!=""){
				errorMsg = "加密串校验出错:"+result;
				return "error";
			}else{
				List<String> li = new ArrayList<String>();
				if(!("".equals(linkedNbr))){
					String[] accnbr2 = linkedNbr.split(",");
					for(int i=0;i<accnbr2.length;i++){
						li.add(accnbr2[i]);
					}
				}
				user.setLinkedAccnbr(li);
				user.setLoginType(loginType);
				session.put("userInfo", user);
				return "success";
			}
		}catch (Exception e) {
			e.printStackTrace();
			errorMsg = "登陆失败";
			return "error";
		}
		
	}
	
	@Action(value = "exit",results = {
			@Result(name = "success", location = "/web/index.htm"),
			@Result(name = "error", location = "/web/error.jsp") })
	public String exit(){
		
		try{
			session.put("userInfo", null);
			return "success";
		}catch (Exception e) {
			e.printStackTrace();
			errorMsg = "操作失败";
			return "error";
		}
		
	}
	
	/**
	 * @package
	 * @author 甘雨波
	 * @description  验证加密
	 * @date 2009-10-21
	 * @param cityCode
	 * @param accnbr
	 * @param loginType
	 * @param dateStr
	 * @param MAC
	 * @return
	 */
	public String identityVisa(String cityCode,String accnbr,String loginType,String dateStr,String MAC) {
		String result = "";
		boolean stop = true;
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 
		
		String privatekey = "aljOciAwemlDdfsaEdeorFdo";

		Date date;
		
		//log.info(cityCode+" "+accnbr+" "+loginType+" "+dateStr+" "+MAC);
		
		try {
			//验证时间戳
			date = df.parse(dateStr);
			long lTime 	= date.getTime();//请求时间
			long now 	= (new Date()).getTime(); //当前时间
			long diff = 0;
			if (now>lTime)
				diff=now-lTime;
			else
				diff=lTime-now;
			long min	= diff/(60*1000); //转换成分钟
			if (min<=10){
				stop=false;
			}else{
				result="请求时间戳超时";
			}
			
			//认证码验证
			if (!stop){
				String vStr = cityCode+accnbr+loginType+dateStr;

				String str = DocryptoSecret.byte2hex(DocryptoSecret.encryptMode(privatekey.getBytes(), vStr.getBytes()));//3DES加密
				String DES 	=  new String(str);
				String MD5Str 	= com.doone.basefun.MD5.getMD5ofString(DES);//MD5加密
				
				System.out.println("MD5Str:"+MD5Str);
				if(MD5Str.equals(MAC)){
					stop=false;
				}else{
					result="非法认证码(MAC)";
				}
			} 
		} catch (java.text.ParseException e) {
			e.printStackTrace();
			result="执行时发生异常";
		}
		return result;
	}
	
	@Action("createCheckWord")
	public void createCheckWord(){
		
		try{
			String code = "";
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					org.apache.struts2.StrutsStatics.HTTP_REQUEST);
			
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
			Random random = new Random();
	        String str="abcdefghigklmnopqrstuvwxyz0123456789";
	        StringBuffer sb = new StringBuffer();
	        int length = str.length();
	        int location = 0;
	        for(int i=0;i<4;i++){
	        	location =random.nextInt(length);
	        	String str1 = str.substring(location,location+1);
	        	sb.append(str1);
	        }
	       String verifyCode = sb.toString();    
	        
	        HttpSession session = request.getSession(true);
	        session.setAttribute("verifyCode", verifyCode);
	        System.out.println(verifyCode);
	        response.setContentType("image/gif");
	        ServletOutputStream out = response.getOutputStream();
	        
	        BufferedImage image = new BufferedImage(130,50,BufferedImage.TYPE_INT_RGB);
	        Graphics gra = image.getGraphics();
	        gra.setColor(Color.white);
	        gra.fillRect(0,0,image.getWidth(),image.getHeight());
	        gra.setColor(new Color(random.nextInt(30*30*30)));
	        gra.setFont(new Font("宋体", Font.PLAIN, 40));
	        gra.drawString(verifyCode, 25, 35);
	        
	        for(int i=0;i<100;i++){
	            gra.setColor(new Color(random.nextInt(255*255*255)));
	            int x = random.nextInt(image.getWidth());
	            int y = random.nextInt(image.getHeight());
	            gra.drawLine(x, y, x+1, y+1);
	        }
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
	        encoder.encode(image);
	        code = verifyCode;
	        out.close();
		}catch (Exception e) {
		
		}
		
		
	}
	@Action(value = "checkAdminLogin",  results = {
			@Result(name = "success", location = "/admin/admin.jsp"),
			@Result(name = "error", location = "/admin/login.jsp") })
	public String adminLogin(){
		
		try{
			log.info(checkWord);
			log.info(session.get("verifyCode").toString());
			if(!checkWord.equals(session.get("verifyCode").toString())){
				errorMsg = "验证码错误";
				return "error";
			}else{
				if((!"a".equals(userName))||(!"a".equals(passWord))){
					errorMsg = "密码验证出错";
					return "error";
				}else{
					session.put("isAdminLogined", "true");
					return "success";
				}
			}
		}catch (Exception e) {
			errorMsg = "系统繁忙,请你稍候再试";
			return "error";
		}
	}
	

	public void setLinkedNbr(String linkedNbr) {
		this.linkedNbr = linkedNbr;
	}
	
	public String getCityCode() {
		return cityCode;
	}


	public void setCityCode(String cityCode) {
		this.cityCode = cityCode;
	}


	public String getAccnbr() {
		return accnbr;
	}


	public void setAccnbr(String accnbr) {
		this.accnbr = accnbr;
	}


	public String getLinkedNbr() {
		return linkedNbr;
	}

	

	public String getTimdeStr() {
		return timdeStr;
	}

	public void setTimdeStr(String timdeStr) {
		this.timdeStr = timdeStr;
	}

	public String getCheckStr() {
		return checkStr;
	}

	public void setCheckStr(String checkStr) {
		this.checkStr = checkStr;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public String getLoginType() {
		return loginType;
	}

	public void setLoginType(String loginType) {
		this.loginType = loginType;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	public String getCheckWord() {
		return checkWord;
	}

	public void setCheckWord(String checkWord) {
		this.checkWord = checkWord;
	}
	
	
	
}
